package com.fh.controller.building;

import com.fh.controller.base.BaseController;
import com.fh.controller.system.tools.errorutils;
import com.fh.entity.Page;
import com.fh.entity.system.User;
import com.fh.service.attachment.AttachmentService;
import com.fh.service.building.BuildingService;
import com.fh.service.building.FloorService;
import com.fh.service.building.RecordService;
import com.fh.service.building.UnitService;
import com.fh.service.building.contract.ContractService;
import com.fh.service.building.room.RoomService;
import com.fh.service.dictionary.DictionaryService;
import com.fh.service.role.ShsRoleService;
import com.fh.service.system.user.UserService;
import com.fh.util.*;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.docx4j.convert.out.FORenderer;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.text.Collator;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;

import static com.fh.controller.system.tools.GetDatalayui.getLData;
import static com.fh.controller.system.tools.GetDatalayui.getPData;


/**
 * 类名称：BuildingController
 * 创建人：FH
 * 创建时间：2017-09-05
 */
@Controller
@RequestMapping(value = "/building")
public class BuildingController extends BaseController {

    @Resource(name = "buildingService")
    private BuildingService buildingService;
    @Resource(name = "unitService")
    private UnitService unitService;
    @Resource(name = "floorService")
    private FloorService floorService;
    @Resource(name = "roomService")
    private RoomService roomService;
    @Resource(name = "attachmentService")
    private AttachmentService attachmentService;
    @Resource(name = "contractService")
    private ContractService contractService;
    @Resource(name = "shsRoleService")
    private ShsRoleService roleService;
    @Resource(name = "userService")
    private UserService userService;
    @Resource(name = "recordService")
    private RecordService recordService;
    @Resource(name="dictionaryService")
    private DictionaryService dictionaryService;

    /**
     * 返回json
     */
    @RequestMapping(value = "/json",produces = "text/html;charset=UTF-8")
    @ResponseBody
    public Object json(Page page) {
        PageData pd = new PageData();
        Map<String, Object> map = new HashMap<String, Object>();
        List<PageData> varList;
        String datalayui = null;

        //获取当前登录用户
        Subject currentUser = SecurityUtils.getSubject();
        Session session = currentUser.getSession();
        User user = (User) session.getAttribute(Const.SESSION_USER);

        try {
            //测试分页 导出为layui的json数据
            pd = this.getPageData();
            pd.put("USER_ID", user.getUSER_ID());
            getPData(page, pd);//必填 2参
            varList = buildingService.list(page);    //列出Building列表
            datalayui = getLData(page, varList);//必填 2参
        } catch (Exception e) {
            logger.error(e.toString(), e);
        } finally {
            logAfter(logger);
        }
        return datalayui;
    }

    /**
     * 楼宇列表
     */
    @RequestMapping(value = "/list")
    @ResponseBody
    public PageData list() {
        logBefore(logger, "Building列表");
        PageData res = new PageData();
        PageData pd = this.getPageData();

        //获取当前登录用户
        Subject currentUser = SecurityUtils.getSubject();
        Session session = currentUser.getSession();
        User user = (User) session.getAttribute(Const.SESSION_USER);

        try {

            if (user.getUSER_TYPE().equals("95bb91515192430bb7a6b5d0a0876542") || pd.get("ADMIN_TYPE") != null) {
                pd.put("USER_ID", user.getUSER_ID());
                List<PageData> list = buildingService.listAll(pd);
                res.put("data", list);
            } else {
                //暂时注释 因为无法获取移动端传来的用户信息
                PageData dataAuthPd = new PageData();
                dataAuthPd.put("USER_ID", user.getUSER_ID());
                List<PageData> data = roleService.dataAuthListByUserId(dataAuthPd);
                String s = "";
                if (data != null && data.size() > 0) {
                    for (int i = 0; i < data.size(); i++) {
                        s += data.get(i).getString("DATA_ID") + ",";
                    }
                }
                pd.put("DATA_IDS", s);
                pd.put("USER_ID", user.getUSER_ID());
                List<PageData> list = buildingService.listAll(pd);
                res.put("data", list);
            }
            res.put("errcode", "0");
            res.put("errmsg", "ok");
        } catch (Exception e) {
            logger.error(e.toString(), e);
            res.put("data", "");
            res.put("errcode", "1");
            res.put("errmsg", e.toString());
        }
        return res;
    }

    /**
     * 首页楼宇左侧 list列表  8
     */
    @RequestMapping(value = "/listArr")
    @ResponseBody
    public PageData listArr(HttpServletRequest request) {
        logBefore(logger, "Building列表");
        PageData res = new PageData();
        PageData pd = this.getPageData();

        //获取当前登录用户
        Subject currentUser = SecurityUtils.getSubject();
        Session session = currentUser.getSession();
        User user = (User) session.getAttribute(Const.SESSION_USER);

        try {
            //获取域名地址 用于组装图片全路径
            StringBuffer url = request.getRequestURL();
            String tempContextUrl = url.delete(url.length() - request.getRequestURI().length(), url.length()).append("/").toString();
            List<PageData> list = new ArrayList<>();
            if ("95bb91515192430bb7a6b5d0a0876542".equals(user.getUSER_TYPE())) {
                pd.put("USER_ID", user.getUSER_ID());
                list = buildingService.listArr(pd);
            } else {
                PageData dataAuthPd = new PageData();
                dataAuthPd.put("USER_ID", user.getUSER_ID());
                List<PageData> data = roleService.dataAuthListByUserId(dataAuthPd);
                String s = "dataAuth";
                if (data != null && data.size() > 0) {
                    for (int i = 0; i < data.size(); i++) {
                        s += data.get(i).getString("DATA_ID") + ",";
                    }
                }
                pd.put("USER_ID", user.getUSER_ID());
                pd.put("DATA_IDS", s);
                list = buildingService.listAll(pd);
            }
            //计算总面积
            int TotalAREA=0;
            for(PageData lists:list){
                    //查询房间面积 动态 待修改2017年12月7日 11:32:30
                    PageData pdroom = new PageData();
                    pdroom.put("BUILDING_ID", lists.get("BUILDING_ID").toString());
                    List<PageData> buildingArea= roomService.buildingArea(pdroom); //计算楼宇面积
                    //TODO 如果创建了楼宇没有创建房间，则此处会报空指针异常 2017-12-18
                    if (buildingArea.get(0) != null) {
                        BigDecimal   b  =   new BigDecimal(buildingArea.get(0).get("BUILDING_AREA").toString());
                        float   f1   =  b.setScale(2, BigDecimal.ROUND_HALF_UP).floatValue();
                        lists.put("BUILDING_AREA",f1);
                    } else {
                        lists.put("BUILDING_AREA",0);
                    }

            }
            for(int i=0;i<list.size();i++){
                PageData att=new PageData();
                att.put("id",list.get(i).get("BUILDING_ID"));
                List<PageData> attachmentData = attachmentService.findByOId(att);//查看附件
                if(attachmentData.size()>0){
                    list.get(i).put("IMG",tempContextUrl+attachmentData.get(0).get("PATH"));
                }
            }
            res.put("TotalAREA",TotalAREA);//总面积
            res.put("data", list);
            res.put("errcode", "0");
            res.put("errmsg", "ok");
        } catch (Exception e) {
            logger.error(e.toString(), e);
            res.put("data", "");
            res.put("errcode", "1");
            res.put("errmsg", e.toString());
        }
        return res;
    }
    /**
     * 首页商圈json列表
     */
    @RequestMapping(value = "/listArrjson")
    @ResponseBody
    public Object listArrjson(Page page) {
        PageData pd = new PageData();
        Map<String, Object> map = new HashMap<String, Object>();
        List<PageData> varList;
        String datalayui = null;
        try {
            //测试分页 导出为layui的json数据
            pd = this.getPageData();
            getPData(page, pd);//必填 2参
            varList =  buildingService.listArr(pd);    //列出Building列表
            datalayui = getLData(page, varList);//必填 2参
        } catch (Exception e) {
            logger.error(e.toString(), e);
        } finally {
            logAfter(logger);
        }
        return datalayui;
    }
    /**
     * 新增
     */
    @RequestMapping(value = "/save")
    @ResponseBody
    public PageData save() {
        logBefore(logger, "新增Building");
        PageData res = new PageData();
        PageData data = this.getPageData();

        //获取当前登录用户
        Subject currentUser = SecurityUtils.getSubject();
        Session session = currentUser.getSession();
        User user = (User) session.getAttribute(Const.SESSION_USER);
        try {
            Map map1 = JSONHelper.json2Map(data.toString());
            Map map2 = JSONHelper.json2Map(map1.get("DATA").toString());
            JSONObject BUILDING = (JSONObject) map2.get("BUILDING");
            JSONArray ATTACHMENT = (JSONArray) map2.get("ATTACHMENT");
            String buildingId = this.get32UUID();
            // 保存楼宇信息
            if (BUILDING != null && !BUILDING.equals("")) {
                PageData pd = new PageData();

                pd.put("BUILDING_ID", buildingId);    //主键
                pd.put("IS_DELETED", 0); //是否删除
                pd.put("SORT", 0); //排序
                pd.put("CREATE_ID", user.getUSER_ID()); //创建时间
                pd.put("CREATE_DATE", new DateUtil().getTime()); //创建时间

                pd.put("BUILDING_NAME", BUILDING.get("BUILDING_NAME"));
                pd.put("BUILDING_AREA", BUILDING.get("BUILDING_AREA"));
                pd.put("LEAS_AREA", BUILDING.get("LEAS_AREA"));
                pd.put("VACANT_AREA", BUILDING.get("VACANT_AREA"));
                pd.put("INVEST_AREA", BUILDING.get("INVEST_AREA"));
                pd.put("AVG_RENT", BUILDING.get("AVG_RENT"));
                pd.put("SETT_COMPANY", BUILDING.get("SETT_COMPANY"));
                pd.put("BUILDING_HIGH", BUILDING.get("BUILDING_HIGH"));
                pd.put("BUSINESS_ID", BUILDING.get("BUSINESS_ID"));
                pd.put("BUILDING_LNG", BUILDING.get("BUILDING_LNG"));
                pd.put("BUILDING_LAT", BUILDING.get("BUILDING_LAT"));
                pd.put("IS_OPEN", BUILDING.get("IS_OPEN"));
                pd.put("BUILDING_ADDRESS", BUILDING.get("BUILDING_ADDRESS"));
                pd.put("BUILDING_INFO", BUILDING.get("BUILDING_INFO"));
                pd.put("floorStart", BUILDING.get("floorStart"));
                pd.put("floorEnd", BUILDING.get("floorEnd"));

                buildingService.save(pd);


                //保存全局记录
                PageData SystemPd = new PageData();
                SystemPd.put("ID", this.get32UUID());//主键
                SystemPd.put("IS_DEL", 0); //是否删除
                SystemPd.put("SORT", 0); //排序
                SystemPd.put("CREATE_ID", user.getUSER_ID()); //创建用户
                SystemPd.put("CREATE_DATE", new DateUtil().getTime()); //创建时间
                SystemPd.put("DETAILS","新增楼宇");
                SystemPd.put("OPERA_TIME",new DateUtil().getTime());
                SystemPd.put("OPERATOR",user.getNAME());
                SystemPd.put("IP",user.getIP());
                SystemPd.put("OP_PD",pd.toString());
                recordService.SaveSystem(SystemPd);


                PageData unitPd = pd;
                int unitStart = Integer.valueOf(BUILDING.getString("unitStart"));
                int unitEnd = Integer.valueOf(BUILDING.getString("unitEnd"));
                if (unitStart > unitEnd) {
                    for (int i = unitStart; i >= unitEnd; i--) {
                        unitPd.put("UNIT_ID", this.get32UUID());
                        unitPd.put("UNIT_NAME", i);
                        unitService.save(unitPd);
                        PageData floorPd = pd;
                        floorPd.put("UNIT_ID", unitPd.get("UNIT_ID"));
                        addFloor(floorPd);
                    }
                } else {
                    for (int i = unitStart; i <= unitEnd; i++) {
                        unitPd.put("UNIT_ID", this.get32UUID());
                        unitPd.put("UNIT_NAME", i);
                        unitService.save(unitPd);
                        PageData floorPd = pd;
                        floorPd.put("UNIT_ID", unitPd.get("UNIT_ID"));
                        addFloor(floorPd);
                    }
                }

            }

            //  保存附件信息
            if (ATTACHMENT.size() > 0) {
                for (int i = 0; i < ATTACHMENT.size(); i++) {
                    PageData pd = new PageData();
                    JSONObject jo = (JSONObject) ATTACHMENT.get(i);
                    pd.put("ID", this.get32UUID());    //主键
                    pd.put("OID", buildingId);
                    pd.put("NAME", jo.get("name"));
                    pd.put("SIZE", jo.get("size"));
                    pd.put("EXT", jo.get("ext"));
                    pd.put("PATH", jo.get("url"));
                    pd.put("TYPE", "building");
                    pd.put("SORT", i + 1);
                    pd.put("REMARK", "");
                    pd.put("CREATE_TIME", new DateUtil().getTime());
                    pd.put("CREATE_ID", user.getUSER_ID());
                    pd.put("IS_DELETED", 0);
                    attachmentService.saveAttachment(pd);
                }
            }

            res.put("data", "");
            res.put("errcode", "0");
            res.put("errmsg", "ok");
        } catch (Exception e) {
            logger.error(e.toString(), e);
            res.put("data", "");
            res.put("errcode", "1");
            res.put("errmsg", e.toString());
        }

        return res;
    }

    void addFloor(PageData pd) throws Exception {

        int floorStart = Integer.valueOf(pd.getString("floorStart"));
        int floorEnd = Integer.valueOf(pd.getString("floorEnd"));
        for (int i = floorStart; i <= floorEnd; i++) {
            pd.put("FLOOR_ID", this.get32UUID());
            pd.put("FLOOR_NAME", i);
            if (i != 0) {
                floorService.save(pd);
            }
        }
    }


    /**
     * 修改
     */
    @RequestMapping(value = "/edit")
    @ResponseBody
    public PageData edit() {
        logBefore(logger, "修改Building");
        PageData res = new PageData();
        PageData pd = this.getPageData();

        //获取当前登录用户
        Subject currentUser = SecurityUtils.getSubject();
        Session session = currentUser.getSession();
        User user = (User) session.getAttribute(Const.SESSION_USER);

        try {
            JSONArray unitList = JSONHelper.toJSONArray(pd.getString("unitList"));
            JSONArray floorList = JSONHelper.toJSONArray(pd.getString("floorList"));
            if (pd.getString("unitList") != null){
                for (int i = 0; i < unitList.size(); i++) {
                    JSONObject unit = unitList.getJSONObject(i);
                    PageData unitPd = new PageData();
                    if (unit.get("UNIT_ID") == null || unit.get("UNIT_ID").equals("")){
                        unitPd.put("UNIT_ID", this.get32UUID());
                        unitPd.put("UNIT_NAME", unit.get("UNIT_NAME"));
                        unitPd.put("IS_DELETED", unit.get("IS_DELETED")); //是否删除
                        unitPd.put("IS_OPEN", unit.get("IS_OPEN")); //是否开启
                        unitPd.put("SORT", 0); //排序
                        unitPd.put("CREATE_ID", user.getUSER_ID()); //创建人
                        unitPd.put("CREATE_DATE", new DateUtil().getTime()); //创建时间
                        unitPd.put("BUSINESS_ID", pd.get("BUSINESS_ID"));
                        unitPd.put("BUILDING_ID", pd.get("BUILDING_ID"));
                        unitService.save(unitPd);
                    } else {
                        unitPd.put("UNIT_ID", unit.get("UNIT_ID"));
                        unitPd.put("UNIT_NAME", unit.get("UNIT_NAME"));
                        unitPd.put("IS_DELETED", unit.get("IS_DELETED")); //是否删除
                        unitPd.put("IS_OPEN", unit.get("IS_OPEN")); //是否开启
                        unitService.edit(unitPd);
                    }
                }
            }

            if (pd.getString("floorList") != null){
                for (int i = 0; i < floorList.size(); i++) {
                    JSONObject floor = floorList.getJSONObject(i);
                    PageData floorPd = new PageData();
                    if (floor.get("FLOOR_ID") == null || floor.get("FLOOR_ID").equals("")){
                        floorPd.put("FLOOR_ID", this.get32UUID());
                        floorPd.put("UNIT_ID", floor.get("UNIT_ID"));
                        floorPd.put("FLOOR_NAME", floor.get("FLOOR_NAME"));
                        floorPd.put("IS_DELETED", floor.get("IS_DELETED")); //是否删除
                        floorPd.put("IS_OPEN", floor.get("IS_OPEN")); //是否开启
                        floorPd.put("SORT", 0); //排序
                        floorPd.put("CREATE_ID", user.getUSER_ID()); //创建人
                        floorPd.put("CREATE_DATE", new DateUtil().getTime()); //创建时间
                        floorPd.put("BUSINESS_ID", pd.get("BUSINESS_ID"));
                        floorPd.put("BUILDING_ID", pd.get("BUILDING_ID"));
                        floorService.save(floorPd);
                    } else {
                        floorPd.put("FLOOR_ID", floor.get("FLOOR_ID"));
                        floorPd.put("FLOOR_NAME", floor.get("FLOOR_NAME"));
                        floorPd.put("IS_DELETED", floor.get("IS_DELETED")); //是否删除
                        floorPd.put("IS_OPEN", floor.get("IS_OPEN")); //是否开启
                        floorService.edit(floorPd);
                    }
                }
            }

            buildingService.edit(pd);
            //保存全局记录
            PageData SystemPd = new PageData();
            SystemPd.put("ID", this.get32UUID());//主键
            SystemPd.put("IS_DEL", 0); //是否删除
            SystemPd.put("SORT", 0); //排序
            SystemPd.put("CREATE_ID", user.getUSER_ID()); //创建用户
            SystemPd.put("CREATE_DATE", new DateUtil().getTime()); //创建时间
            SystemPd.put("DETAILS","修改楼宇");
            SystemPd.put("OPERA_TIME",new DateUtil().getTime());
            SystemPd.put("OPERATOR",user.getNAME());
            SystemPd.put("IP",user.getIP());
            SystemPd.put("OP_PD",pd.toString());
            recordService.SaveSystem(SystemPd);
            res.put("data", "");
            res.put("errcode", "0");
            res.put("errmsg", "ok");
        } catch (Exception e) {
            logger.error(e.toString(), e);
            res.put("data", "");
            res.put("errcode", "1");
            res.put("errmsg", e.toString());
        }

        return res;
    }


    /**
     * 修改带图坐标
     */
    @RequestMapping(value = "/editBuilding")
    @ResponseBody
    public PageData editBuilding() {
        logBefore(logger, "修改Building");
        PageData res = new PageData();
        PageData data = this.getPageData();

        //获取当前登录用户
        Subject currentUser = SecurityUtils.getSubject();
        Session session = currentUser.getSession();
        User user = (User) session.getAttribute(Const.SESSION_USER);

        try {

            Map map1 = JSONHelper.json2Map(data.toString());
            Map map2 = JSONHelper.json2Map(map1.get("DATA").toString());
            JSONObject BUILDING = (JSONObject) map2.get("BUILDING");
            JSONArray ATTACHMENT = (JSONArray) map2.get("ATTACHMENT");
            String buildingId = BUILDING.getString("BUILDING_ID");

            JSONArray unitList = JSONHelper.toJSONArray(BUILDING.getString("unitList"));
            JSONArray floorList = JSONHelper.toJSONArray(BUILDING.getString("floorList"));
            if (BUILDING.getString("unitList") != null){
                for (int i = 0; i < unitList.size(); i++) {
                    JSONObject unit = unitList.getJSONObject(i);
                    PageData unitPd = new PageData();
                    if (unit.get("UNIT_ID") == null || unit.get("UNIT_ID").equals("")){
                        unitPd.put("UNIT_ID", this.get32UUID());
                        unitPd.put("UNIT_NAME", unit.get("UNIT_NAME"));
                        unitPd.put("IS_DELETED", unit.get("IS_DELETED")); //是否删除
                        unitPd.put("IS_OPEN", unit.get("IS_OPEN")); //是否开启
                        unitPd.put("SORT", 0); //排序
                        unitPd.put("CREATE_ID", user.getUSER_ID()); //创建人
                        unitPd.put("CREATE_DATE", new DateUtil().getTime()); //创建时间
                        unitPd.put("BUSINESS_ID", BUILDING.get("BUSINESS_ID"));
                        unitPd.put("BUILDING_ID", BUILDING.get("BUILDING_ID"));
                        unitService.save(unitPd);
                    } else {
                        unitPd.put("UNIT_ID", unit.get("UNIT_ID"));
                        unitPd.put("UNIT_NAME", unit.get("UNIT_NAME"));
                        unitPd.put("IS_DELETED", unit.get("IS_DELETED")); //是否删除
                        unitPd.put("IS_OPEN", unit.get("IS_OPEN")); //是否开启
                        unitService.edit(unitPd);
                    }
                }
            }

            if (BUILDING.getString("floorList") != null){
                for (int i = 0; i < floorList.size(); i++) {
                    JSONObject floor = floorList.getJSONObject(i);
                    PageData floorPd = new PageData();
                    if (floor.get("FLOOR_ID") == null || floor.get("FLOOR_ID").equals("")){
                        floorPd.put("FLOOR_ID", this.get32UUID());
                        floorPd.put("UNIT_ID", floor.get("UNIT_ID"));
                        floorPd.put("FLOOR_NAME", floor.get("FLOOR_NAME"));
                        floorPd.put("IS_DELETED", floor.get("IS_DELETED")); //是否删除
                        floorPd.put("IS_OPEN", floor.get("IS_OPEN")); //是否开启
                        floorPd.put("SORT", 0); //排序
                        floorPd.put("CREATE_ID", user.getUSER_ID()); //创建人
                        floorPd.put("CREATE_DATE", new DateUtil().getTime()); //创建时间
                        floorPd.put("BUSINESS_ID", BUILDING.get("BUSINESS_ID"));
                        floorPd.put("BUILDING_ID", BUILDING.get("BUILDING_ID"));
                        floorService.save(floorPd);
                    } else {
                        floorPd.put("FLOOR_ID", floor.get("FLOOR_ID"));
                        floorPd.put("FLOOR_NAME", floor.get("FLOOR_NAME"));
                        floorPd.put("IS_DELETED", floor.get("IS_DELETED")); //是否删除
                        floorPd.put("IS_OPEN", floor.get("IS_OPEN")); //是否开启
                        floorService.edit(floorPd);
                    }
                }
            }

            // 保存楼宇信息
            if (BUILDING != null && !BUILDING.equals("")) {
                PageData pd = new PageData();
                pd.put("BUILDING_ID", buildingId);    //主键
                pd.put("BUILDING_NAME", BUILDING.get("BUILDING_NAME"));
                pd.put("BUILDING_AREA", BUILDING.get("BUILDING_AREA"));
                pd.put("LEAS_AREA", BUILDING.get("LEAS_AREA"));
                pd.put("VACANT_AREA", BUILDING.get("VACANT_AREA"));
                pd.put("INVEST_AREA", BUILDING.get("INVEST_AREA"));
                pd.put("AVG_RENT", BUILDING.get("AVG_RENT"));
                pd.put("SETT_COMPANY", BUILDING.get("SETT_COMPANY"));
                pd.put("BUILDING_HIGH", BUILDING.get("BUILDING_HIGH"));
                pd.put("BUSINESS_ID", BUILDING.get("BUSINESS_ID"));
                pd.put("BUILDING_LNG", BUILDING.get("BUILDING_LNG"));
                pd.put("BUILDING_LAT", BUILDING.get("BUILDING_LAT"));
                pd.put("IS_OPEN", BUILDING.get("IS_OPEN"));
                pd.put("BUILDING_ADDRESS", BUILDING.get("BUILDING_ADDRESS"));
                pd.put("BUILDING_INFO", BUILDING.get("BUILDING_INFO"));
                pd.put("floorStart", BUILDING.get("floorStart"));
                pd.put("floorEnd", BUILDING.get("floorEnd"));
                buildingService.edit(pd);
                //保存全局记录
                PageData SystemPd = new PageData();
                SystemPd.put("ID", this.get32UUID());//主键
                SystemPd.put("IS_DEL", 0); //是否删除
                SystemPd.put("SORT", 0); //排序
                SystemPd.put("CREATE_ID", user.getUSER_ID()); //创建用户
                SystemPd.put("CREATE_DATE", new DateUtil().getTime()); //创建时间
                SystemPd.put("DETAILS","修改楼宇");
                SystemPd.put("OPERA_TIME",new DateUtil().getTime());
                SystemPd.put("OPERATOR",user.getNAME());
                SystemPd.put("IP",user.getIP());
                SystemPd.put("OP_PD",pd.toString());
                recordService.SaveSystem(SystemPd);
            }


            PageData p = new PageData();
            p.put("ID", buildingId);
            attachmentService.deleteAttachmentByOid(p);
            //  保存附件信息
            if (ATTACHMENT.size() > 0) {
                for (int i = 0; i < ATTACHMENT.size(); i++) {
                    PageData pd = new PageData();
                    JSONObject jo = (JSONObject) ATTACHMENT.get(i);
                    pd.put("ID", this.get32UUID());    //主键
                    pd.put("OID", buildingId);
                    pd.put("NAME", jo.get("name"));
                    pd.put("SIZE", jo.get("size"));
                    pd.put("EXT", jo.get("ext"));
                    pd.put("PATH", jo.get("url"));
                    pd.put("TYPE", "building");
                    pd.put("SORT", i + 1);
                    pd.put("REMARK", "");
                    pd.put("CREATE_TIME", new DateUtil().getTime());
                    pd.put("CREATE_ID", user.getUSER_ID());
                    pd.put("IS_DELETED", 0);
                    attachmentService.saveAttachment(pd);
                }
            }

            res.put("data", "");
            res.put("errcode", "0");
            res.put("errmsg", "ok");
        } catch (Exception e) {
            logger.error(e.toString(), e);
            res.put("data", "");
            res.put("errcode", "1");
            res.put("errmsg", e.toString());
        }

        return res;
    }

    /**
     * 通过ID获取详情信息
     */
    @RequestMapping(value = "/info")
    @ResponseBody
    public PageData info() {
        logBefore(logger, "Building详情");
        PageData res = new PageData();
        PageData pd = this.getPageData();

        try {
            PageData data = buildingService.findById(pd);
            pd.put("id", pd.get("BUILDING_ID"));
            List<PageData> attachmentData = attachmentService.findByOId(pd);
            List<PageData> unitList = unitService.findByBuildingId(pd);
            List<PageData> floorList = new ArrayList<>();
            for (int i = 0; i < unitList.size(); i++) {
                PageData p = new PageData();
                p.put("UNIT_ID", unitList.get(i).get("UNIT_ID"));
                List<PageData> floor = floorService.findByUnitId(p);
                p.put("floorList", floor);
                floorList.add(p);
            }

            List<PageData> itemList = roomService.findItemByBuildingId(pd);

            res.put("data", data);
            res.put("unitList", unitList);
            res.put("floorList", floorList);
            res.put("itemList", itemList);
            res.put("attachmentData", attachmentData);
            res.put("errcode", "0");
            res.put("errmsg", "ok");
        } catch (Exception e) {
            logger.error(e.toString(), e);
            res.put("data", "");
            res.put("errcode", "1");
            res.put("errmsg", e.toString());
        }
        return res;
    }
    /**
     * 通过UNIT_ID获取详情信息
     */
    @RequestMapping(value = "/floorInfo")
    @ResponseBody
    public PageData floorInfo() {
        logBefore(logger, "floor详情");
        PageData res = new PageData();
        PageData pd = this.getPageData();

        try {
            List<PageData> floorList = floorService.findByUnitId(pd);

            res.put("data", floorList);
            res.put("errcode", "0");
            res.put("errmsg", "ok");
        } catch (Exception e) {
            logger.error(e.toString(), e);
            res.put("data", "");
            res.put("errcode", "1");
            res.put("errmsg", e.toString());
        }

        return res;
    }

    /**
     * 删除
     */
    @RequestMapping(value = "/delete")
    @ResponseBody
    public PageData delete() {
        PageData res = new PageData();
        PageData pd = this.getPageData();
        //获取当前登录用户
        Subject currentUser = SecurityUtils.getSubject();
        Session session = currentUser.getSession();
        User user = (User) session.getAttribute(Const.SESSION_USER);
        try {
            pd = this.getPageData();
            buildingService.delete(pd);
            //保存全局记录
            PageData SystemPd = new PageData();
            SystemPd.put("ID", this.get32UUID());//主键
            SystemPd.put("IS_DEL", 0); //是否删除
            SystemPd.put("SORT", 0); //排序
            SystemPd.put("CREATE_ID", user.getUSER_ID()); //创建用户
            SystemPd.put("CREATE_DATE", new DateUtil().getTime()); //创建时间
            SystemPd.put("DETAILS","删除楼宇");
            SystemPd.put("OPERA_TIME",new DateUtil().getTime());
            SystemPd.put("OPERATOR",user.getNAME());
            SystemPd.put("IP",user.getIP());
            SystemPd.put("OP_PD",pd.toString());
            recordService.SaveSystem(SystemPd);
            res.put("data", "");
            res.put("errcode", "0");
            res.put("errmsg", "ok");
        } catch (Exception e) {
            logger.error(e.toString(), e);
            res.put("data", "");
            res.put("errcode", "1");
            res.put("errmsg", e.toString());
        }
        return res;
    }

    /**
     * 批量删除
     */
    @RequestMapping(value = "/deleteAll")
    @ResponseBody
    public Object deleteAll() {
        logBefore(logger, "批量删除Building");
        PageData pd = new PageData();
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            pd = this.getPageData();
            List<PageData> pdList = new ArrayList<PageData>();
            String DATA_IDS = pd.getString("DATA_IDS");
            if (null != DATA_IDS && !"".equals(DATA_IDS)) {
                String ArrayDATA_IDS[] = DATA_IDS.split(",");
                buildingService.deleteAll(ArrayDATA_IDS);
                pd.put("msg", "ok");
            } else {
                pd.put("msg", "no");
            }
            pdList.add(pd);
            map.put("list", pdList);
        } catch (Exception e) {
            logger.error(e.toString(), e);
        } finally {
            logAfter(logger);
        }
        return AppUtil.returnObject(pd, map);
    }

    /**
     * 去新增页面
     */
    @RequestMapping(value = "/goAdd")
    public ModelAndView goAdd() {
        logBefore(logger, "去新增Building页面");
        ModelAndView mv = this.getModelAndView();
        PageData pd = new PageData();
        pd = this.getPageData();
        try {
            mv.setViewName("build/building/building_edit");
            mv.addObject("msg", "save");
            mv.addObject("pd", pd);
        } catch (Exception e) {
            logger.error(e.toString(), e);
        }
        return mv;
    }

    /**
     * 去修改页面
     */
    @RequestMapping(value = "/goEdit")
    public ModelAndView goEdit() {
        logBefore(logger, "去修改Building页面");
        ModelAndView mv = this.getModelAndView();
        PageData pd = new PageData();
        pd = this.getPageData();
        try {
            pd = buildingService.findById(pd);    //根据ID读取
            mv.setViewName("build/building/building_edit");
            mv.addObject("msg", "edit");
            mv.addObject("pd", pd);
        } catch (Exception e) {
            logger.error(e.toString(), e);
        }
        return mv;
    }

    /**
     * 去楼层页面
     */
    @RequestMapping(value = "/goRoom")
    public ModelAndView goRoom() {
        logBefore(logger, "去楼层页面");
        ModelAndView mv = this.getModelAndView();

        //获取当前登录用户
        Subject currentUser = SecurityUtils.getSubject();
        Session session = currentUser.getSession();
        User user = (User) session.getAttribute(Const.SESSION_USER);

        PageData pd = new PageData();
        PageData pdroom = new PageData();
        pd = this.getPageData();
        try {
            if(!"".equals(pd.get("BUILDING_ID").toString())) {
                pdroom.put("UNIT_ID", pd.get("UNIT_ID").toString());
                pd = buildingService.findById(pd);    //根据ID读取
                pdroom.put("BUILDING_ID", pd.get("BUILDING_ID").toString());
                pdroom.put("USER_ID", user.getUSER_ID());
                List<PageData> roomList = roomService.listAll(pdroom);    //列出Building列表
                List<PageData> floorList = roomService.listFloor(pdroom);
                List<Map<String, String>> newlist = new ArrayList<>();
                //列出Building列表
                //TODO 判断某个房间是否有合同

                float total = 0;
                float totalLSF = 0;
                float lm = 0;
                int ff;
                String prolistdata = "";
                for (int i = 0; i < roomList.size(); i++) {
                    //统计 每层的面积
                    Map<String, String> map = new HashMap<>();
                    for (int k = 0; k < floorList.size(); k++) {
                        if (roomList.get(i).containsKey("FLOOR_ID")) {
                            if (floorList.get(k).get("FLOOR_ID").toString().equals(roomList.get(i).get("FLOOR_ID").toString())) {
                                //System.out.println(floorList.get(k).get("FLOOR_NAME"));
                                //System.out.println(roomList.get(i).get("ROOM_AREA"));
                                //把循环出来的 每层的面积 相加
                                total = total + Float.parseFloat(roomList.get(i).get("ROOM_AREA").toString());
                                map.put("area", roomList.get(i).get("ROOM_AREA").toString());
                                map.put("num", floorList.get(k).get("FLOOR_NAME").toString());
                                newlist.add(map);

                                //System.out.println(floorList.get(k));
                            }
                        }
                        //把分组过的楼层面积 组装起来
                        float totalArea = 0;
                        int ra = 0;
                        for (int s = 0; s < newlist.size(); s++) {
                            if (newlist.get(s).get("num").equals(floorList.get(k).get("FLOOR_NAME").toString())) {
                                totalArea = totalArea + Float.parseFloat(newlist.get(s).get("area").toString());
                                BigDecimal b = new BigDecimal(totalArea);
                                float f1 = b.setScale(2, BigDecimal.ROUND_HALF_UP).floatValue();
                                floorList.get(k).put("FloorArea", f1);
                                ra++;
                                floorList.get(k).put("FloorRoomNum", ra);
                            }
                        }
                    }
                    PageData pds = new PageData();
                    pds.put("ROOM_ID", roomList.get(i).get("ROOM_ID"));
                    List<PageData> list = contractService.listAll(pds);//通过房间id 获取合同基本信息
                    if (list.size() > 0) {
                        if ("5".equals(list.get(0).get("CHECK_STATE").toString())) {
                            roomList.get(i).put("iscon", 5);//退租待审核
                        }
                        if ("8".equals(list.get(0).get("CHECK_STATE").toString())) {
                            roomList.get(i).put("iscon", 1);//退租不通过
                        }
                        if ("1".equals(list.get(0).get("CHECK_STATE").toString())) {
                            roomList.get(i).put("iscon", 1);//审核通过
                        }
                        if ("2".equals(list.get(0).get("CHECK_STATE").toString())) {
                            roomList.get(i).put("iscon", 0);//审核不通过
                        }
                        if ("01".equals(list.get(0).get("CHECK_STATE").toString())) {
                            roomList.get(i).put("iscon", 5);//新建待审核
                        }
                        if ("02".equals(list.get(0).get("CHECK_STATE").toString())) {
                            roomList.get(i).put("iscon", 5);//新建待审核
                        }
                        if ("03".equals(list.get(0).get("CHECK_STATE").toString())) {
                            roomList.get(i).put("iscon", 5);//新建待审核
                        }
                        if ("04".equals(list.get(0).get("CHECK_STATE").toString())) {
                            roomList.get(i).put("iscon", 5);//新建待审核
                        }
                        if ("9".equals(list.get(0).get("CHECK_STATE").toString())) {
                            roomList.get(i).put("iscon", 0);//合同作废
                        }
                        if ("11".equals(list.get(0).get("CHECK_STATE").toString())) {
                            roomList.get(i).put("iscon", 1);//合同作废审核不通过
                        }
                        if ("43ac91b97d144550aed7ea1c01de60ee".equals(list.get(0).get("STATE").toString())) {
                            roomList.get(i).put("iscon", 0);//已完结 的合同
                        }
                    } else {
                        roomList.get(i).put("iscon", 0);//无合同
                    }
                    //临时房处理方法
                    float totalArea = 0;
                    if (!roomList.get(i).containsKey("FLOOR_ID")) {
                        //System.out.println(roomList.get(i));
                        totalLSF = totalLSF + Float.parseFloat(roomList.get(i).get("ROOM_AREA").toString());
                        PageData pdYd = new PageData();
                        pdYd.put("ROOM_ID", roomList.get(i).get("ROOM_ID"));
                        List<PageData> listYd = contractService.listAll(pdYd);//
                        if (listYd.size() > 0) {
                            if ("5".equals(listYd.get(0).get("CHECK_STATE").toString())) {
                                roomList.get(i).put("iscon", 5);//退租待审核
                            }
                            if ("8".equals(listYd.get(0).get("CHECK_STATE").toString())) {
                                roomList.get(i).put("iscon", 1);//退租不通过
                            }
                            if ("1".equals(listYd.get(0).get("CHECK_STATE").toString())) {
                                roomList.get(i).put("iscon", 1);//审核通过
                            }
                            if ("2".equals(listYd.get(0).get("CHECK_STATE").toString())) {
                                roomList.get(i).put("iscon", 0);//审核不通过
                            }
                            if ("01".equals(listYd.get(0).get("CHECK_STATE").toString())) {
                                roomList.get(i).put("iscon", 5);//新建待审核
                            }
                            if ("02".equals(listYd.get(0).get("CHECK_STATE").toString())) {
                                roomList.get(i).put("iscon", 5);//新建待审核
                            }
                            if ("03".equals(listYd.get(0).get("CHECK_STATE").toString())) {
                                roomList.get(i).put("iscon", 5);//新建待审核
                            }
                            if ("04".equals(listYd.get(0).get("CHECK_STATE").toString())) {
                                roomList.get(i).put("iscon", 5);//新建待审核
                            }
                            if ("9".equals(listYd.get(0).get("CHECK_STATE").toString())) {
                                roomList.get(i).put("iscon", 0);//合同作废
                            }
                            if ("11".equals(listYd.get(0).get("CHECK_STATE").toString())) {
                                roomList.get(i).put("iscon", 1);//合同作废审核不通过
                            }
                        } else {
                            roomList.get(i).put("iscon", 0);//无合同
                        }
//                    prolistdata+=roomList.get(i).get("ROOM_NUM");
                        PageData roomtype = new PageData();
                        roomtype.put("ID", roomList.get(i).get("ROOM_TYPE"));
                        roomtype.put("USER_ID", user.getUSER_ID());
                        roomList.get(i).put("isLSF", roomtype.get("ID"));//临时房标识类型
                        prolistdata += roomtype.get("ID")+",";
                        roomList.get(i).put("totalArea", totalLSF);//临时房标识
                        lm++;
                        //System.out.println(111);
                    }

                }
                //处理 所有的 项目类型
                PageData ProjectType = new PageData();
                ProjectType.put("USER_ID", user.getUSER_ID());
                List<PageData> prolist = dictionaryService.project_type(ProjectType);
                mv.addObject("prolist", prolist);//其他类型
                mv.addObject("prolistdata", prolistdata);//其他类型具体值
                mv.addObject("totalAreaLSF", totalLSF);//临时房的 面积
                mv.addObject("totalRoomNum", lm);//临时房的 面积
                mv.addObject("floorlist", floorList);//楼层列表
                mv.addObject("floornum", floorList.size());//总层数
                mv.addObject("roomList", roomList);//房间列表
                mv.setViewName("build/building/building_room");
                mv.addObject("msg", "edit");
                mv.addObject("pd", pd);
            }else {
                mv.setViewName("build/building/no_room");
            }
        } catch (Exception e) {
            logger.error(e.toString(), e);
        }
        return mv;
    }
    /**
     * 通过楼宇id获取 房间信息
     */
    @RequestMapping(value = "/roomInfo")
    @ResponseBody
    public PageData roomInfo() {
        logBefore(logger, "room详情");
        PageData res = new PageData();
        PageData pd = this.getPageData();
        PageData pdroom = new PageData();
        try {
            pdroom.put("UNIT_ID", pd.get("UNIT_ID").toString());
            pd = buildingService.findById(pd);    //根据ID读取
            pdroom.put("BUILDING_ID", pd.get("BUILDING_ID").toString());
            List<PageData> roomList = roomService.listAll(pdroom);    //列出Building列表
            List<PageData> floorList = roomService.listFloor(pdroom);    //列出楼层
            List<PageData> roomzu= roomService.roomArea(pdroom); //列出楼宇已租面积
            List<PageData> buildingArea= roomService.buildingArea(pdroom); //计算楼宇面积
            //System.out.println(roomzu.get(0).get("ROOM_AREA"));
            res.put("floorlist", floorList);//楼层列表
            res.put("floornum",floorList.size());//总层数
            res.put("roomList", roomList);//房间列表
            if(buildingArea.size()>0){
                // TODO 没有加判断，当有楼宇没有房间时候会报空指针 2017-12-18
                if (null!=buildingArea.get(0)) {
                    double f = (double) buildingArea.get(0).get("BUILDING_AREA");
                    BigDecimal b = new BigDecimal(f);
                    double f1 = b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                    res.put("BUILDING_AREA",f1);
                } else {
                    res.put("BUILDING_AREA",0);
                }
            }else{
                res.put("BUILDING_AREA",0);
            }
            roomzu.remove(null);
            if(roomzu.size()>0){
                res.put("roomzu", roomzu.get(0).get("ROOM_AREA"));//楼宇房间面积
                res.put("COMPANY_IN", roomzu.get(0).get("COMPANY_IN"));//入驻企业数目
            }else {
                res.put("roomzu", "0");//楼宇房间面积
                res.put("COMPANY_IN", "0");//入驻企业数目
            }
            res.put("data",pd);
            res.put("errcode", "0");
            res.put("errmsg", "ok");
        } catch (Exception e) {
            logger.error(e.toString(), e);
            res.put("data", "");
            res.put("errcode", "1");
            res.put("errmsg", "请选择楼宇");
        }

        return res;
    }

    /*
     * 导出到excel
     * @return
     */
    @RequestMapping(value = "/excel")
    public ModelAndView exportExcel() {
        logBefore(logger, "导出Building到excel");
        ModelAndView mv = new ModelAndView();
        PageData pd = new PageData();
        pd = this.getPageData();
        try {
            Map<String, Object> dataMap = new HashMap<String, Object>();
            List<String> titles = new ArrayList<String>();
            titles.add("楼宇");    //1
            titles.add("总面积");    //2
            titles.add("已租面积");    //3
            titles.add("空置面积");    //4
            titles.add("可招商面积");    //5
            titles.add("在租均价");    //6
            titles.add("入驻企业");    //7
            dataMap.put("titles", titles);
            List<PageData> varOList = buildingService.listAll(pd);
            List<PageData> varList = new ArrayList<PageData>();
            for (int i = 0; i < varOList.size(); i++) {
                PageData vpd = new PageData();
                vpd.put("var1", varOList.get(i).getString("NNAME"));    //1
                vpd.put("var2", varOList.get(i).getString("AREA"));    //2
                vpd.put("var3", varOList.get(i).getString("LEAS_AREA"));    //3
                vpd.put("var4", varOList.get(i).getString("VACANT_AREA"));    //4
                vpd.put("var5", varOList.get(i).getString("INVEST_AREA"));    //5
                vpd.put("var6", varOList.get(i).getString("AVG_RENT"));    //6
                vpd.put("var7", varOList.get(i).getString("SETT_COMPANY"));    //7
                varList.add(vpd);
            }
            dataMap.put("varList", varList);
            ObjectExcelView erv = new ObjectExcelView();
            mv = new ModelAndView(erv, dataMap);
        } catch (Exception e) {
            logger.error(e.toString(), e);
        }
        return mv;
    }

    /* ===============================权限================================== */
    public Map<String, String> getHC() {
        Subject currentUser = SecurityUtils.getSubject();  //shiro管理的session
        Session session = currentUser.getSession();
        return (Map<String, String>) session.getAttribute(Const.SESSION_QX);
    }
    /* ===============================权限================================== */

    @InitBinder
    public void initBinder(WebDataBinder binder) {
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        binder.registerCustomEditor(Date.class, new CustomDateEditor(format, true));
    }
    /* ===============================app接口================================= */




    /**
     * app 楼宇列表接口
     */
    @RequestMapping(value = "/listBuildingApp",produces = "text/html;charset=UTF-8")
    @ResponseBody
    public Object listBuildingApp(Page page,HttpServletRequest request) {
        PageData pd = new PageData();
        PageData pds = new PageData();
        Map<String, Object> map = new HashMap<String, Object>();
        List<PageData> varList;
        String datalayui = null;
        //获取当前登录用户  移动端获取当前登录用户 并传给此接口
//        Subject currentUser = SecurityUtils.getSubject();
//        Session session = currentUser.getSession();
//        User user = (User) session.getAttribute(Const.SESSION_USER);
        try {
            pd = this.getPageData();
            pds.put("page",pd.get("page"));
            pds.put("limit",pd.get("row"));
            if(null != pd.get("businessId") && !"".equals(pd.get("businessId"))){
                pds.put("businessId",pd.get("businessId"));
            }
            if(null != pd.get("time") && !"".equals(pd.get("time"))){
                pds.put("time",pd.get("time"));
            }
            if(null != pd.get("state") && !"".equals(pd.get("state"))){
                pds.put("state",pd.get("state"));
            }
            getPData(page, pds);
            List<PageData> list;

            // 数据权限开始
            if(null!=pd.get("userid")){
                pd.put("USER_ID",pd.get("userid"));
                PageData puser=userService.findByUserId(pd);
                if ("95bb91515192430bb7a6b5d0a0876542".equals(puser.get("USER_TYPE"))) {
                    pd.put("USER_ID",pd.get("userid"));
                    page.setPd(pd);
                    list= buildingService.listBuildingApp(page);
                } else {
                    //暂时注释 因为无法获取移动端传来的用户信息 2018年1月9日 17:05:02
                    if(null!=pd.get("userid")){
                        PageData dataAuthPd = new PageData();
                        dataAuthPd.put("USER_ID",pd.get("userid"));
                        List<PageData> data = roleService.dataAuthListByUserId(dataAuthPd);
                        String s = "";
                        if (data != null && data.size() > 0) {
                            for (int i = 0; i < data.size(); i++) {
                                s += data.get(i).getString("DATA_ID") + ",";
                            }
                        }
                        pd.put("USER_ID", pd.get("userid"));
                        pd.put("DATA_IDS", s);
                        page.setPd(pd);
                        list= buildingService.listBuildingApp(page);
                    }else {
                        page.setPd(pd);
                        list= buildingService.listBuildingApp(page);
                    }

                }
            } else {
                page.setPd(pd);
                list= buildingService.listBuildingApp(page);
            }

            // 数据权限结束
            //获取域名地址 用于组装图片全路径
            StringBuffer url = request.getRequestURL();
            String tempContextUrl = url.delete(url.length() - request.getRequestURI().length(), url.length()).append("/").toString();
            List<String> listdata=  new ArrayList<>();
            for(int i=0;i<list.size();i++){
                PageData pdss = new PageData();
                pds.put("BUILDING_ID",list.get(i).get("id"));//根据每个楼宇的id
                List<PageData> roombill= buildingService.Roomdetail(pds);  //返回房间基本信息 房间的数量 查出商圈下的每个楼宇的信息
                PageData att=new PageData();
                att.put("id",list.get(i).get("id"));
                List<PageData> attachmentData = attachmentService.findByOId(att);//查看附件
                if(attachmentData.size()>0){
                    list.get(i).put("IMG",tempContextUrl+attachmentData.get(0).get("PATH"));
                }
                PageData pdroom = new PageData();
                pdroom.put("BUILDING_ID", list.get(i).get("id"));
                List<PageData> roomzu= roomService.roomArea(pdroom); //列出楼宇已租面积
                List<PageData> buildingArea= roomService.buildingArea(pdroom); //计算楼宇总面积
                buildingArea.remove(null);
                    if(buildingArea.size()>0){
                        list.get(i).put("build_area", buildingArea.get(0).get("BUILDING_AREA"));
                    }else {
                        list.get(i).put("build_area", 0.00);
                    }

                //Float.parseFloat(list.get(i).get("build_area").toString())-
                if(roomzu.get(0).containsKey("ROOM_AREA")){
                    double f = (double) roomzu.get(0).get("ROOM_AREA");
                    BigDecimal b = new BigDecimal(f);
                    double f1 = b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                    list.get(i).put("ROOMED",f1+"㎡");//已租面积
                    float ROOM_AREA=Float.parseFloat(buildingArea.get(0).get("BUILDING_AREA").toString())-Float.parseFloat(roomzu.get(0).get("ROOM_AREA").toString());
                    BigDecimal b1 = new BigDecimal(ROOM_AREA);
                    double f2 = b1.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                    list.get(i).put("ROOMNOT",f2+"㎡");//未租面积
                }else {
                    list.get(i).put("ROOMED",0.00+"㎡");
                    list.get(i).put("ROOMNOT",0.00+"㎡");//未租面积
                }
                if (roomzu.get(0).size() == 1) {
                    if (buildingArea.size() > 0) {
                        double f = (double) buildingArea.get(0).get("BUILDING_AREA");
                        BigDecimal b = new BigDecimal(f);
                        double f1 = b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                        list.get(i).put("ROOMNOT", f1 + "㎡");//未租面积
                    } else {
                        list.get(i).put("ROOMNOT", 0.00 + "㎡");//未租面积
                    }
                }
                double f = (double) list.get(i).get("build_area");
                BigDecimal b = new BigDecimal(f);
                double f1 = b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                list.get(i).put("build_area",f1+"㎡");//楼宇总面积
                list.get(i).put("roomnums",roombill.size());//每个楼的 楼宇数目
            }
            varList = list;
            datalayui = getLData(page, varList);
        } catch (Exception e) {
            logger.error(e.toString(), e);
        } finally {
            logAfter(logger);
        }
        return datalayui;
    }



    /**
     * app 楼宇列表接口
     */
   /* @RequestMapping(value = "/listBuildingApp")
    @ResponseBody
    public PageData listBuildingApp(HttpServletRequest request) {
        PageData res = new PageData();
        PageData pd = this.getPageData();
        try {
            pd = this.getPageData();
            List<PageData> list= buildingService.listBuildingApp(pd);

            //获取域名地址 用于组装图片全路径
            StringBuffer url = request.getRequestURL();
            String tempContextUrl = url.delete(url.length() - request.getRequestURI().length(), url.length()).append("/").toString();
            List<String> listdata=  new ArrayList<>();
            for(int i=0;i<list.size();i++){
                PageData pds = new PageData();
                pds.put("BUILDING_ID",list.get(i).get("id"));//根据每个楼宇的id
                List<PageData> roombill= buildingService.Roomdetail(pds);  //返回房间基本信息 房间的数量 查出商圈下的每个楼宇的信息
                PageData att=new PageData();
                att.put("id",list.get(i).get("id"));
                List<PageData> attachmentData = attachmentService.findByOId(att);//查看附件
                if(attachmentData.size()>0){
                    list.get(i).put("IMG",tempContextUrl+"ceshi/"+attachmentData.get(0).get("PATH"));
                }
                PageData pdroom = new PageData();
                pdroom.put("BUILDING_ID", list.get(i).get("id"));
                List<PageData> roomzu= roomService.roomArea(pdroom); //列出楼宇已租面积
                List<PageData> buildingArea= roomService.buildingArea(pdroom); //计算楼宇总面积
                list.get(i).put("build_area", buildingArea.get(0).get("BUILDING_AREA"));
                //Float.parseFloat(list.get(i).get("build_area").toString())-
                if(roomzu.get(0).containsKey("ROOM_AREA")){
                    double f = (double) roomzu.get(0).get("ROOM_AREA");
                    BigDecimal b = new BigDecimal(f);
                    double f1 = b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                    list.get(i).put("ROOMED",f1+"㎡");//已租面积
                    float ROOM_AREA=Float.parseFloat(buildingArea.get(0).get("BUILDING_AREA").toString())-Float.parseFloat(roomzu.get(0).get("ROOM_AREA").toString());
                    BigDecimal b1 = new BigDecimal(ROOM_AREA);
                    double f2 = b1.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                    list.get(i).put("ROOMNOT",f2+"㎡");//未租面积
                }else {
                    list.get(i).put("ROOMED",0.00+"㎡");
                    list.get(i).put("ROOMNOT",0.00+"㎡");//未租面积
                }
                if(roomzu.get(0).size()==1){
                    double f = (double) buildingArea.get(0).get("BUILDING_AREA");
                    BigDecimal b = new BigDecimal(f);
                    double f1 = b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                    list.get(i).put("ROOMNOT",f1+"㎡");//未租面积
                }
                double f = (double) list.get(i).get("build_area");
                BigDecimal b = new BigDecimal(f);
                double f1 = b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                list.get(i).put("build_area",f1+"㎡");//楼宇总面积
                list.get(i).put("roomnums",roombill.size());//每个楼的 楼宇数目
            }
            res.put("data", list);
            res.put("errcode", "0");
            res.put("errmsg", "ok");
        } catch (Exception e) {
            logger.error(e.toString(), e);
            res.put("data", "");
            res.put("errcode", "1");
            res.put("errmsg", e.toString());
        }
        return res;
    }*/

    /**
     * 楼宇详情接口app
     */
    @RequestMapping(value = "/Buildingdetail")
    @ResponseBody
    public PageData Buildingdetail(HttpServletRequest request) {
        PageData res = new PageData();
        PageData pd = this.getPageData();
        try {
            pd = this.getPageData();
            pd.put("UNIT_ID", pd.get("UNIT_ID"));
            List<PageData> listbuild = buildingService.Buildingdetail(pd); //返回基本楼宇信息
            List<PageData> roombill = buildingService.Roomdetail(pd);//返回所有房间
//            PageData pd_other = new PageData();
//            pd_other.put("BUILDING_ID", pd.get("BUILDING_ID"));
//            List<PageData> room_other = buildingService.Roomdetail(pd_other);//返回其他房 临时房 移动房等数据
            List<PageData> ROOMED = buildingService.RoomROOMED(pd);   //返回房间已租数目
            List<PageData> listbill = buildingService.Billdetail(pd); //返回水 水费
            List<PageData> listELE = buildingService.BillELE(pd); //返回电费
            List<PageData> floorList = roomService.listFloor(pd);    //列出楼层
            List<PageData> listINPUT = buildingService.BillINPUT(pd); //本月收入
            List<PageData> roomssno = new ArrayList<>();//没有楼层的 其他类型的项目
            listbill.remove(null);
            listELE.remove(null);
            if (listbill.size() > 0) {
                double f = (double) listbill.get(0).get("WATER");
                BigDecimal b = new BigDecimal(f);
                double f1 = b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                listbuild.get(0).put("WATER", String.format("%.2f", f));
            } else {
                listbuild.get(0).put("WATER", "0.00");
            }
            if (listELE.size() > 0) {
                double f = (double) listELE.get(0).get("ELE");
                BigDecimal b = new BigDecimal(f);
                double f1 = b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                listbuild.get(0).put("ELE", String.format("%.2f", f));
            } else {
                listbuild.get(0).put("ELE", "0.00");
            }
            listINPUT.remove(null);
            if (listINPUT.size() > 0) {
                String f = listINPUT.get(0).get("INPUT").toString();
                listbuild.get(0).put("INPUT", f);
            } else {
                listbuild.get(0).put("INPUT", "0.00");
            }
            //TODO 依次把 楼层 和房间 分离出来
            List<Object> newroombill = new ArrayList<>();
            List<Object> FLOOR = new ArrayList<>();
            List<Object> UNITLIST = new ArrayList<>();//存储单元数据
            if (floorList.size() > 0) {
                for (int j = 0; j < floorList.size(); j++) {
                    Map<Object, Object> FLOORS = new HashMap<>();
                    List<Object> roomss = new ArrayList<>();//有楼层的
                    Map<Object, Object> FLOORsss = new HashMap<>();//存楼层数组
                    if (roombill.size() > 0) {
                        roombill.get(0).get("FLOOR_NAME");
                        FLOORsss.put("FLOORS", floorList.get(j).get("FLOOR_NAME"));
                        for (PageData roombills : roombill) {
                            String s = String.valueOf(floorList.get(j).get("FLOOR_NAME"));
                            if (null != roombills.get("FLOOR_NAME")) {
                                if (s.equals(roombills.get("FLOOR_NAME").toString())) {
                                    //System.out.println(roombills.get("FLOOR_NAME").toString());
                                    List<Object> ROOMS = new ArrayList<>();
                                    PageData pds = new PageData();
                                    pds.put("ROOM_ID", roombills.get("ROOM_ID"));
                                    List<PageData> list = contractService.listAll(pds);//通过房间id 获取合同基本信息
                                    //fixme 暂时处理有合同 和无合同
                                    if (list.size() > 0) {
                                        if ("1".equals(list.get(0).get("CHECK_STATE").toString())) {
                                            roombills.put("ROOM_STATE", "在租");//在租状态
                                        }
                                    } else {
                                        roombills.put("ROOM_STATE", "暂无");//退租待审核
                                    }
                                    ROOMS.add(roombills);
                                    roomss.addAll(ROOMS);
                                }
                            }
                            FLOORS.put("ROOMSLIST", roomss);
                            FLOORsss.putAll(FLOORS);
                        }
                    }
                    newroombill.add(FLOORsss);
                }

            }
            //TODO 查询没有楼层的数据
            for (PageData roombills : roombill) {
                //没有楼层 处理方法
                if (!roombills.containsKey("FLOOR_NAME")) {
                    List<PageData> ROOMS = new ArrayList<>();

                    PageData pds = new PageData();
                    pds.put("ROOM_ID", roombills.get("ROOM_ID"));
                    List<PageData> list = contractService.listAll(pds);//通过房间id 获取合同基本信息
                    //fixme 暂时处理有合同 和无合同
                    if (list.size() > 0) {
                        if ("1".equals(list.get(0).get("CHECK_STATE").toString())) {
                            roombills.put("ROOM_STATE", "在租");//在租状态
                        }
                    } else {
                        roombills.put("ROOM_STATE", "暂无");//退租待审核
                    }

                    ROOMS.add(roombills);
                    roomssno.addAll(ROOMS);
                }
            }
            HashSet<PageData> h = new HashSet(roomssno);
            // 定义一个中文排序器
            Comparator c = Collator.getInstance(Locale.CHINA);
            List<PageData> listno = new ArrayList<>();//存放没有房间号的 临时房 list
            for (PageData h1 : h) {
                listno.add(h1);
            }
            SortUtil.sort(listno, "ROOM_NUM", "asc");//根据房间号 做一个排序造作
            Map<Object, Object> FLOORS = new HashMap<>();
            Map<PageData, PageData> FLOORsss = new HashMap<>();//临时房的map集合

            //获取 所有的 项目类型
            PageData ProjectType = new PageData();
            ProjectType.put("USER_ID", pd.get("USER_ID"));
            List<PageData> prolist = dictionaryService.project_type(ProjectType);//取出所有的项目类型
            //放 停车场 广告牌 绿地 等等
            List<PageData> RoomOther = new ArrayList<>();
            List<Object> RoomOtherAll = new ArrayList<>();
            List<Object> other_types = new ArrayList<>();//存其他所有类型
            for (int i = 0; i < prolist.size(); i++) {
                Map<Object, Object> other_type = new HashMap<>();
//                RoomOtherAll.add(listno);
                //TODO 把每个存在其他类型 分类 放到属于 各自类型的 其他类型下
                List<Object> roomos = new ArrayList<>();//存放归类出来的数据
                for(PageData room_other_single:listno){
                    if(room_other_single.get("ROOM_TYPE").toString().indexOf(prolist.get(i).get("ID").toString())!=-1){
                        other_type.put("FLOORS",prolist.get(i).get("NAME"));//存放其他类型的 名称
                        List<Object> ROOMS = new ArrayList<>();
                        ROOMS.add(room_other_single);
                        roomos.addAll(ROOMS);
                    }
                    other_type.put("ROOMSLIST",roomos);//存放其他类型的房间
                }
                if(other_type.size()==2){//为了排除没有房间的其他类型
                    other_types.add(other_type);//把其他类型的map放到list中
                }
            }
            newroombill.addAll(other_types);
            listbuild.get(0).put("LIST", newroombill);
            listbuild.get(0).put("FLOORS", floorList.size());
            //附件 详情图
            //TODO 获取域名地址 用于组装图片全路径
            StringBuffer url = request.getRequestURL();
            String tempContextUrl = url.delete(url.length() - request.getRequestURI().length(), url.length()).append("/").toString();
            List<String> listdata = new ArrayList<>();
            PageData att = new PageData();
            att.put("id", pd.get("BUILDING_ID"));
            List<PageData> attachmentData = attachmentService.findByOId(att);//查看附件
            if (attachmentData.size() > 0) {
                for (int k = 0; k < attachmentData.size(); k++) {
                    listdata.add(tempContextUrl + attachmentData.get(k).get("PATH"));//存放楼宇img 数组
                }
                //listimg.put("img",tempContextUrl+attachmentData.get(0).get("PATH"));
            }
            List<Object> IMGLIST = new ArrayList<>();
            IMGLIST.add(0, "IMG");
            listbuild.get(0).put("IMG", listdata);
            listbuild.get(0).put("roomnums", roombill.size());//楼宇的 总共房间数
            listbuild.get(0).put("ROOMED", ROOMED.get(0).get("ROOMED"));//楼宇的 已租数目
            int ROOMEDS = Integer.parseInt(roombill.size() + "") - Integer.parseInt(ROOMED.get(0).get("ROOMED").toString());//计算楼宇的可招租数目
            listbuild.get(0).put("ROOMS", ROOMEDS);//楼宇的 可招租数目
            //TODO 临时房处理方法
            float totalArea = 0;
            if (roombill.size() > 0) {
                if (!roombill.get(0).containsKey("FLOOR_ID")) {
                    roombill.get(0).put("isLSF", 1);//临时房标识
                }
            }
            PageData pdroom = new PageData();
            pdroom.put("BUILDING_ID", listbuild.get(0).get("id"));
            List<PageData> buildingArea = roomService.buildingArea(pdroom); //计算楼宇总面积
            buildingArea.remove(null);
            if (buildingArea.size() > 0) {
                double f = (double) buildingArea.get(0).get("BUILDING_AREA");
                BigDecimal b = new BigDecimal(f);
                double f1 = b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                listbuild.get(0).put("build_area", f1);
            } else {
                listbuild.get(0).put("build_area", 0.00);
            }
            List<Object> newlist = new ArrayList<Object>();
            PageData ress = new PageData();
            //list.addAll(list1);
            res = errorutils.getResults(listbuild, pd);
        } catch (Exception e) {
            logger.error(e.toString(), e);
            res.put("data", "");
            res.put("errcode", "1");
            res.put("errmsg", e.toString());
        }
        return res;
    }

    public static List<PageData> getIntersection(List<PageData> list1,
                                                List<PageData> list2) {
        List<PageData> result = new ArrayList<PageData>();
        for (PageData  integer: list2) {//遍历list1
            if (list1.contains(integer)) {//如果存在这个数
                result.add(integer);//放进一个list里面，这个list就是交集
            }
        }
        return result;
    }


    /**
     * 单元列表
     */
    @RequestMapping(value = "/unitList")
    @ResponseBody
    public PageData unitList() {
        logBefore(logger, "Building详情");
        PageData res = new PageData();
        PageData pd = this.getPageData();

        try {
            pd.put("id", pd.get("BUILDING_ID"));
            List<PageData> data = unitService.findByBuildingId(pd);
            res.put("data", data);
            res.put("errcode", "0");
            res.put("errmsg", "ok");
        } catch (Exception e) {
            logger.error(e.toString(), e);
            res.put("data", "");
            res.put("errcode", "1");
            res.put("errmsg", e.toString());
        }
        return res;
    }
}
////////////////////////////////////////////////////////////////////
//                          _ooOoo_                               //
//                         o8888888o                              //
//                         88" . "88                              //
//                         (| ^_^ |)                              //
//                         O\  =  /O                              //
//                      ____/`---'\____                           //
//                    .'  \\|     |//  `.                         //
//                   /  \\|||  :  |||//  \                        //
//                  /  _||||| -:- |||||-  \                       //
//                  |   | \\\  -  /// |   |                       //
//                  | \_|  ''\---/''  |   |                       //
//                  \  .-\__  `-`  ___/-. /                       //
//                ___`. .'  /--.--\  `. . ___                     //
//              ."" '<  `.___\_<|>_/___.'  >'"".                  //
//            | | :  `- \`.;`\ _ /`;.`/ - ` : | |                 //
//            \  \ `-.   \_ __\ /__ _/   .-` /  /                 //
//      ========`-.____`-.___\_____/___.-`____.-'========         //
//                           `=---='                              //
//      ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^        //
//         佛祖保佑       永无BUG     永不修改                  //
////////////////////////////////////////////////////////////////////
